package middlewares

import (
	"context"
	"encoding/json"
	"time"

	"go-micro.dev/v5/server"

	"go.uber.org/zap"
)

/**
 * @description 日志中间件
 * @author huwl
 * @date 2025/08/07 16:24:58
 */
func ZapLogWrapper(logger *zap.Logger) server.HandlerWrapper {
	return func(fn server.HandlerFunc) server.HandlerFunc {
		return func(ctx context.Context, req server.Request, rsp interface{}) error {
			start := time.Now()

			// 调用实际的处理函数
			err := fn(ctx, req, rsp)

			duration := time.Since(start)

			// 请求数据转换成json格式
			body := map[string]interface{}{}
			b, _ := json.Marshal(req.Body())
			json.Unmarshal(b, &body)

			// 记录日志
			logFields := []zap.Field{
				zap.String("method", req.Method()),
				zap.Any("header", req.Header()),
				zap.Any("body", body),
				zap.Duration("duration", duration),
			}

			if err != nil {
				logFields = append(logFields,
					zap.Error(err),
					// zap.String("error_code", server.ErrorCode(err)),
				)
				logger.Error("gRPC request failed", logFields...)
			} else {
				logger.Info("gRPC request success", logFields...)
			}

			return err
		}
	}
}
